import 'dart:async';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_more_menu_dialog/common_more_menu_dialog.dart';
import 'package:e_reception_flutter/constants/branch/main_constant.dart';
import 'package:e_reception_flutter/media_library/media_library_index/bean/media_detail_response_bean.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/share_poster_menu_dialog.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/share_repository/share_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_list_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_image_detail_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_style_type_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_page.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_upload_service.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:sharesdk_plugin/sharesdk_defines.dart';
import 'package:sharesdk_plugin/sharesdk_map.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_save_util_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import 'event/refresh_smart_home_index_event.dart';

/// 智能家居图片详情页面
class SmartHomeImageDetailPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomeImageDetailPage";
  final String picid;
  final String videoid;
  final String shid;
  final String picurl;
  final bool isVideo;
  final bool isExample;
  final double scale;

  const SmartHomeImageDetailPage({Key key, this.picid, this.videoid, this.shid, this.picurl, this.isVideo, this.isExample, this.scale}) : super(key:key);

  @override
  _SmartHomeImageDetailPageState createState() => _SmartHomeImageDetailPageState();

  static Future<dynamic> navigatorPush(BuildContext context, String picid,
      String videoid, String shid, String picurl, bool isVideo, bool isExample, double scale){
    return RouterUtils.routeForFutureResult(
        context,
        SmartHomeImageDetailPage(
          picid: picid,
          videoid: videoid,
          shid: shid,
          picurl: picurl,
          isVideo: isVideo,
          isExample: isExample,
          scale: scale,
        ),
        routeName: SmartHomeImageDetailPage.ROUTER
    );
  }
}

class _SmartHomeImageDetailPageState
    extends BaseState<SmartHomeImageDetailPage> {

  SmartHomeStoreDetailViewModel _viewModel;
  String _cacheKey;
  StorePicInfoBean _picInfoBean;
  StreamSubscription _updateStreamSubscription;
  String _picurl;
  bool _isVideo;
  bool _isExample;
  Function _onGetData;
  @override
  void initState() {
    super.initState();
    _picurl = widget?.picurl;
    _isVideo = widget?.isVideo;
    _isExample = widget?.isExample??false;
    _cacheKey = NetApi.GET_STORE_ONE_PIC_DETAIL + (UserRepository.getInstance().authId?? "")
        + widget?.picid;
    _onGetData = (picInfoBean){
      setState(() {
        _picInfoBean = picInfoBean;
      });
    };
    _viewModel = new SmartHomeStoreDetailViewModel(this);
    _viewModel.getImageDetail(context, widget?.picid, _onGetData);
    _updateStreamSubscription =
        VgEventBus.global.on<RefreshSmartHomeIndexEvent>()?.listen((event) {
          _viewModel.getImageDetail(context, widget?.picid, _onGetData);
        });

  }

  @override
  void dispose() {
    super.dispose();
    _updateStreamSubscription?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomInset: false,
          resizeToAvoidBottomPadding: false,
          backgroundColor: Colors.white,
          body: _toMainColumnWidget(),
        )
    );
  }

  Widget _toPlaceHolderWidget() {
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getImageDetailOnLine(widget?.picid, _cacheKey, null, _onGetData),
            loadingOnClick: () => _viewModel
                .getImageDetailOnLine(widget?.picid, _cacheKey, null, _onGetData),
            child: child,
          );
        },
        child: _toMainColumnWidget());
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: [
        _toTopBarWidget(),
        _toScrollWidget(),
      ],
    );
  }

  ///页面标题
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      rightWidget: _toMoreOperationsWidget(),
      rightPadding: 5,
    );
  }

  Widget _toMoreOperationsWidget() {
    return Container(
      width: 120,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Visibility(
            visible: !_isVideo,
            child: _toOperationsWidget("icon_download", (){
              _download();
            }),
          ),
          Visibility(
            visible: !_isVideo,
            child: _toOperationsWidget("icon_share", (){
              _share();
            }),
          ),
          _toOperationsWidget("icon_more_horizontal", (){
            _more();
          }),
        ],
      ),
    );
  }

  ///下载 分享 更多
  Widget _toOperationsWidget(String resource, Function onTap){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        onTap.call();
      },
      child: Container(
        height: 44,
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Image.asset(
            "images/${resource}.png",
            width: 20,
            height: 20,
          ),
        ),
      ),
    );
  }

  ///下载
  _download()async{
    if(_picInfoBean == null){
      return;
    }
    loading(true, msg: "下载中");
    String saveResult =
    await SaveUtils.saveImage(url: _picInfoBean.picurl);
    if(StringUtils.isNotEmpty(saveResult)){
      loading(false);
      if(saveResult == "保存成功"){
        toast("下载成功");
      }else{
        toast(saveResult);
      }
    }
  }
  ///分享
  _share(){
    if(_picInfoBean == null){
      return;
    }
    SharePosterMenuDialog.navigatorPushDialog(context, () {
      RouterUtils.pop(context);
      //直接分享图片
      SSDKMap params = SSDKMap()
        ..setGeneral("AI前台App", "智能家居", null, _picInfoBean?.picurl, "", _picInfoBean?.picurl, "", "", "",
            "", SSDKContentTypes.image);
      _weChatShare(context, params, "00");

    }, () {
      RouterUtils.pop(context);
      //直接分享图片
      SSDKMap params = SSDKMap()
        ..setGeneral("AI前台App", "智能家居", null, _picInfoBean?.picurl, "", _picInfoBean?.picurl, "", "", "",
            "", SSDKContentTypes.image);
      _weChatShare(context, params, "01");

    },
        bgColor: Colors.white,
        splitColor: Color(0xFFF6F7F9),
        textColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        pyqResource:"images/icon_pyq_white.png"
    );
  }

  void _weChatShare(BuildContext context, SSDKMap params, String shareFlag) {
    ShareRepository.getInstance().shareImageToWechat(context, params,
        platforms: ("00" == shareFlag)
            ? ShareSDKPlatforms.wechatTimeline
            : ShareSDKPlatforms.wechatSession);
  }
  ///更多
  _more(){
    Map<String, VoidCallback> map;
    if(_isExample??false){
      map = {
        "删除":()async{
          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "是否确认删除当前文件？",
            cancelText: "取消",
            confirmText: "确认",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            _viewModel.deleteImage(context, widget?.picid, widget?.videoid, widget?.shid);
          }
        }
      };
    }else{
      map = {
        "编辑":()async{
          if(_picInfoBean == null){
            return;
          }
          List<SmartHomeUploadItemBean> uploadList = List();
          uploadList.add(SmartHomeUploadItemBean(
            picid: widget?.picid,
            netUrl: _picInfoBean.picurl,
            videoNetCover: _picInfoBean?.videopic??"",
            videoLocalCover: _picInfoBean?.videopic??"",
            backup: _picInfoBean.backup,
            stid: _picInfoBean?.stid,
            folderWidth: int.parse(_picInfoBean?.picsize?.split("*")[0]),
            folderHeight: int.parse(_picInfoBean?.picsize?.split("*")[1]),
            picstorage:_picInfoBean?.picstorage,
            style: _picInfoBean?.style,
            type: _picInfoBean.type,
          ));
          String cacheKey = NetApi.GET_CATEGORY_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
              + widget?.shid;
          _viewModel.getCategoryOnLine(widget?.shid, cacheKey, null, onGetCategory: (value)async{
            bool result = await SmartHomeUploadPage.navigatorPush(context, uploadList[0], uploadList, widget?.shid, value, router: SmartHomeImageDetailPage.ROUTER);
          });
        },
        "删除":()async{
          bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
            title: "提示",
            content: "是否确认删除当前文件？",
            cancelText: "取消",
            confirmText: "确认",
            confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            cancelBgColor: Color(0xFFF6F7F9),
            titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            contentColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
            widgetBgColor: Colors.white,
          );
          if (result ?? false) {
            _viewModel.deleteImage(context, widget?.picid, widget?.videoid, widget?.shid);
          }
        }
      };
    }
    CommonMoreMenuDialog.navigatorPushDialog(context, map,
      bgColor: Colors.white,
      splitColor: Color(0xFFF6F7F9),
      textColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      lineColor: Color(0xFFEEEEEE),
    );
  }

  Widget _toScrollWidget(){
    return Expanded(
      child: ListView(
        padding: EdgeInsets.all(0),
        children: [
          _toImageWidget(),
          SizedBox(height: 12,),
          _toInfoWidget(),
        ],
      ),
    );

  }


  Widget _toImageWidget(){
    double imgWidth = ScreenUtils.screenW(context);
    double imgHeight = imgWidth * widget?.scale;
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_isVideo){
          VgPhotoPreview.single(
              context,
              _picInfoBean?.picurl,
              loadingCoverUrl: _picurl,
              loadingImageQualityType: ImageQualityType.high,
              photoPreviewType: PhotoPreviewType.video
          );
        }else{
          VgPhotoPreview.single(
              context,
              _picurl,
              loadingImageQualityType: ImageQualityType.high,
          );
        }

      },
      child: Stack(
        children: [
          VgCacheNetWorkImage(
              _picurl,
              width: imgWidth,
              height: imgHeight,
              imageQualityType: ImageQualityType.original,
              placeWidget: Container(color: Colors.white,)
          ),
          Positioned(
            left: imgWidth/2 - 26,
            top: imgHeight/2 - 26,
            child: Visibility(
              visible: _isVideo,
              child: Opacity(
                opacity: 0.5,
                child: Image.asset(
                  "images/icon_smart_home_video_play.png",
                  width: 60,
                  height: 60,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _toInfoWidget(){
    return ValueListenableBuilder(
      valueListenable: _viewModel?.imageDetailValueNotifier,
      builder:
          (BuildContext context, StorePicInfoBean picInfoBean, Widget child) {
        if(picInfoBean != null){
          _picInfoBean = picInfoBean;
          if(StringUtils.isNotEmpty(_picInfoBean.getCoverUrl())){
            _picurl = _picInfoBean.getCoverUrl();
          }
          _isVideo = _picInfoBean.isVideo();
        }
        return Column(
          children: [
            _toLabelListWidget(picInfoBean),
            Visibility(
                visible: _showLabel(picInfoBean),
                child: SizedBox(height: 8,)
            ),
            _toMediaInfoWidget(picInfoBean, null),
            SizedBox(height: 6,),
            _toBackupWidget(picInfoBean?.backup??""),
            SizedBox(height: 50 + ScreenUtils.getBottomBarH(context),)
          ],
        );
      },);
  }

  Widget _toLabelListWidget(StorePicInfoBean picInfoBean){
    return Visibility(
      visible: _showLabel(picInfoBean),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 15),
        alignment: Alignment.centerLeft,
        child: Wrap(
          spacing: 4.0, // 主轴(水平)方向间距
          runSpacing: 8, // 纵轴（垂直）方向间距
          alignment: WrapAlignment.start, //沿主轴方向居中
          runAlignment: WrapAlignment.start,
          children: _imageWidgetList(picInfoBean),
        ),
      ),
    );
  }

  bool _showLabel(StorePicInfoBean picInfoBean){
    if(StringUtils.isNotEmpty(picInfoBean?.spatialname)){
      return true;
    }
    if(StringUtils.isNotEmpty(picInfoBean?.style)){
      return true;
    }
    return false;
  }

  List<Widget> _imageWidgetList(StorePicInfoBean picInfoBean){
    List<Widget> widgetList = new List();
    if(StringUtils.isNotEmpty(picInfoBean?.spatialname)){
      widgetList.add(_toLabelItemWidget(picInfoBean?.spatialname));
    }
    if(StringUtils.isNotEmpty(picInfoBean?.style)){
      String label = ConstantRepository.of().getStyleNameByStyle(picInfoBean?.style);
      if(StringUtils.isNotEmpty(label)){
        widgetList.add(_toLabelItemWidget(label));
      }
    }
    return widgetList;
  }


  Widget _toLabelItemWidget(String label){
    return ClipRRect(
      borderRadius: BorderRadius.circular(2),
      child: Container(
        padding: EdgeInsets.only(left: 8, top: 2, right: 8, bottom: 2),
        color: Color(0xFFCFD4DB),
        child: Text(
          label??"",
          style: TextStyle(
              fontSize: 11,
              color: ThemeRepository.getInstance().getCardBgColor_21263C()
          ),
        ),
      ),
    );
  }

  ///文件基本信息栏
  Widget _toMediaInfoWidget(StorePicInfoBean picInfoBean, List<AttListBean> attList) {
    String startTime = "";
    String endTime = "";
    int totalPlayNum = 0;
    int num = 0;
    if(attList != null && attList.length > 0){
      if(StringUtils.isNotEmpty(attList[0].startday)&&StringUtils.isNotEmpty(attList[0].endday)){
        startTime = attList[0].startday;
        endTime = attList[0].endday;
        int currentMill = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY)).millisecondsSinceEpoch;
        if(DateTime.parse(startTime).millisecondsSinceEpoch <= currentMill){
          num++;
        }
        for(int i = 1; i < attList.length; i++){
          if(StringUtils.isNotEmpty(attList[i]?.endday) && DateTime.parse(endTime).millisecondsSinceEpoch <= DateTime.parse(attList[i].endday).millisecondsSinceEpoch){
            endTime = attList[i].endday;
          }
          if(StringUtils.isNotEmpty(attList[i]?.startday) && DateTime.parse(startTime).millisecondsSinceEpoch >= DateTime.parse(attList[i].startday).millisecondsSinceEpoch){
            startTime = attList[i].startday;
          }
          if(StringUtils.isNotEmpty(attList[i]?.startday) && DateTime.parse(attList[i].startday).millisecondsSinceEpoch <= currentMill){
            num++;
          }
        }
        int startMill = DateTime.parse(startTime).millisecondsSinceEpoch;
        int endMill = DateTime.parse(endTime).millisecondsSinceEpoch;


        if(endMill > currentMill){
          totalPlayNum = (((currentMill - startMill)~/(1000*3600*24)) + 1);
        }else{
          totalPlayNum = (((endMill - startMill)~/(1000*3600*24)) + 1);
        }
        if(totalPlayNum <= 0){
          totalPlayNum = 0;
        }
      }
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15),
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "尺寸：${picInfoBean?.picsize?.replaceAll("*", "×")??""}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 11,
                      color: Color(0xFF8B93A5),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "文件大小：${picInfoBean?.getPicStorageStr()}",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 11,
                      color: Color(0xFF8B93A5),
                    ),
                  ),
                ),
              ),
            ],
          ),
          SizedBox(
            height: 4,
          ),
          Visibility(
            visible: !_isExample,
            child: Row(
              children: <Widget>[
                Expanded(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "上传人：${picInfoBean?.name??"系统推送"}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 11,
                        color: Color(0xFF8B93A5),
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "上传时间：${TimeUtil.format((picInfoBean?.createtime??0)*1000, dayFormat: DayFormat.Full)}",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 11,
                        color: Color(0xFF8B93A5),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // SizedBox(
          //   height: 4,
          // ),
          // Row(
          //   children: <Widget>[
          //     Container(
          //       alignment: Alignment.centerLeft,
          //       child: Text(
          //         "已在${num??0}台终端播放${totalPlayNum??0}天",
          //         maxLines: 1,
          //         overflow: TextOverflow.ellipsis,
          //         style: TextStyle(
          //           fontSize: 11,
          //           color: Color(0xFF8B93A5),
          //         ),
          //       ),
          //     ),
          //   ],
          // ),
        ],
      ),
    );
  }

  ///备注信息
  Widget _toBackupWidget(String backup){
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 15),
      alignment: Alignment.centerLeft,
      child: Text(
        backup,
        style: TextStyle(
            fontSize: 14,
            color: ThemeRepository.getInstance().getCardBgColor_21263C()
        ),
      ),
    );
  }

}
